import { onMounted, ref } from 'vue'
import service from '@/api/index.js'
const useTableData = (params) => {
	const tableData = ref([])
	const total = ref(0)
	const getTableData = async (data) => {
		let res = await service.post(
			params.getList.url,
			Object.assign(params.getList.params, data),
		)
		tableData.value = res.list
		total.value = res.total
	}

	const delRow = async (delRowUrl, delRowParams, methods) => {
		try {
			methods === 'delete'
				? await service.delete(delRowUrl, delRowParams)
				: await service.post(delRowUrl, delRowParams)
			await getTableData()
			return Promise.resolve()
		} catch (err) {
			return Promise.reject(err)
		}
	}

	const addRow = async (addRowUrl, addRowParams) => {
		try {
			await service.post(addRowUrl, addRowParams)
			await getTableData()
			return Promise.resolve()
		} catch (err) {
			return Promise.reject(err)
		}
	}

	const updateRow = async (updateRowUrl, updateRowParams) => {
		try {
			await service.put(updateRowUrl, updateRowParams)
			await getTableData()
			return Promise.resolve()
		} catch (err) {
			return Promise.reject(err)
		}
	}

	onMounted(async () => {
		await getTableData()
	})

	return {
		tableData,
		total,
		delRow,
		addRow,
		updateRow,
		getTableData,
	}
}
export default useTableData
